package com.example.batch.service;

import com.example.batch.event.BatchTaskMetaEvent;
import com.example.batch.mapper.TMissionMapper;
import com.example.batch.mapper.TTaskMapper;
import com.example.batch.model.TMission;
import com.example.batch.model.TTask;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * TaskService：负责主任务与子任务的持久化
 */
@Service
@RequiredArgsConstructor
public class TaskService {

    private final TMissionMapper missionMapper;
    private final TTaskMapper taskMapper;

    /**
     * 创建主任务（TMission），返回自增主键 missionId
     */
    @Transactional(rollbackFor = Exception.class)
    public Long createMainMission(BatchTaskMetaEvent event) {
        TMission mission = new TMission();
        mission.setBatchId(event.getBatchId());
        mission.setName(event.getName());
        mission.setDescription(event.getDescription());
        mission.setTotalTasks(event.getUrls().size());
        mission.setSuccessCount(0);
        mission.setFailCount(0);
        mission.setProgress(0);
        mission.setStatus("PROCESSING");
        mission.setCreateTime(LocalDateTime.now());
        mission.setUpdateTime(LocalDateTime.now());

        missionMapper.insert(mission);
        // 插入后会回写 mission.id
        return mission.getId();
    }

    /**
     * 创建单个子任务链，返回所有插入的子任务 ID 列表
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> createSingleTask(List<String> urls,
                                       String action,
                                       Long missionId) {
        List<Long> insertedIds = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (String url : urls) {
            TTask task = new TTask();
            task.setMissionId(missionId);
            task.setUrl(url);
            task.setAction(action);
            task.setStatus("PENDING");
            task.setCreateTime(now);
            task.setUpdateTime(now);
            taskMapper.insert(task);
            insertedIds.add(task.getId());
        }
        return insertedIds;
    }

    /**
     * 更新主任务进度和状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMissionProgress(Long missionId, int successCount, int failCount) {
        TMission mission = missionMapper.selectById(missionId);
        if (mission == null) {
            throw new RuntimeException("Mission not found: " + missionId);
        }
        Integer totalTasks = mission.getTotalTasks();
        if (totalTasks == null || totalTasks <= 0) {
            throw new IllegalArgumentException("Total tasks count must be positive");
        }
        int total = totalTasks;
        int done = successCount + failCount;
        int percent = (int) (done * 100.0 / total);

        mission.setSuccessCount(successCount);
        mission.setFailCount(failCount);
        mission.setProgress(percent);
        if (done >= total) {
            mission.setStatus("COMPLETED");
        } else {
            mission.setStatus("PROCESSING");
        }
        mission.setUpdateTime(LocalDateTime.now());
        missionMapper.updateProgressAndStatus(mission);
    }

    /**
     * 查询主任务详情
     */
    public List<TMission> getMissionByBatchId(String batchId) {
        return missionMapper.selectByBatchId(batchId);
    }
}
